package com.cyys.modules.system.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyys.common.annotation.SystemLog;
import com.cyys.common.dataScope.DataScope;
import com.cyys.common.ql.AR;
import com.cyys.common.ql.JSONData;
import com.cyys.common.utils.CommonUtils;
import com.cyys.common.utils.StringUtil;
import com.cyys.common.validate.Detail;
import com.cyys.common.validate.Edit;
import com.cyys.common.validate.Insert;
import com.cyys.modules.core.controller.BaseAction;
import com.cyys.modules.core.sysParam.ParamBasicUtil;
import com.cyys.modules.core.sysParam.ParamConstants;
import com.cyys.modules.core.sysParam.SystemConfigureUtil;
import com.cyys.modules.core.sysParam.SystemConstants;
import com.cyys.modules.system.model.org.Org;
import com.cyys.modules.system.model.user.Role;
import com.cyys.modules.system.model.user.User;
import com.cyys.modules.system.service.org.OrgService;
import com.cyys.modules.system.service.user.RoleService;
import com.cyys.modules.system.service.user.UserService;
import com.google.common.collect.Lists;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.util.*;

@Controller
@RequestMapping("/sys/user")
@Validated
public class UserAction extends BaseAction {

	@Resource
	private UserService userService;

	@Resource
	private RoleService roleService;

	@Resource
	private OrgService orgService;

	@GetMapping("/add/input")
	public String input(String orgId, Model model)  {
		User user = new User();
		String roleScope = getUser().getType();
		if("3".equals(roleScope)){ //本机构权限
			orgId= getUser().getOrgId();
		}
		user.setOrgId(orgId);
		if(getUser().getId().equals("1")){
			model.addAttribute("isDeveloper", "1"); //开发者
		}
		model.addAttribute("user", user);
		model.addAttribute("typeMap", ParamBasicUtil.getParamBasicTypeMap().get(ParamConstants.USER_TYPE));
		model.addAttribute("userType",getUser().getType());
		model.addAttribute("pwdStrength", SystemConfigureUtil.get(SystemConstants.PWD_STRENGTH));
		model.addAttribute(SystemConstants.LOGIN_SMS_CODE_OPEN, SystemConfigureUtil.get(SystemConstants.LOGIN_SMS_CODE_OPEN));
		return "module/system/user/user-input";
	}

	@GetMapping("/edit/input")
	public String editInput(@Validated(Detail.class) User user, Model model)  {
		if(getUser().getId().equals("1")){
			model.addAttribute("isDeveloper", "1"); //开发者
		}
		model.addAttribute("typeMap", ParamBasicUtil.getParamBasicTypeMap().get(ParamConstants.USER_TYPE));
		model.addAttribute("userType",getUser().getType());
		model.addAttribute("pwdStrength", SystemConfigureUtil.get(SystemConstants.PWD_STRENGTH));
		model.addAttribute("user", userService.getById(user.getId()));
		model.addAttribute(SystemConstants.LOGIN_SMS_CODE_OPEN, SystemConfigureUtil.get(SystemConstants.LOGIN_SMS_CODE_OPEN));
		return "module/system/user/user-input";
	}

	@ResponseBody
	@PostMapping("/add/save")
	@SystemLog(module = "系统设置", methods = "系统用户管理-保存用户")
	public AR save(@Validated(Insert.class)User user)  {
		return userService.save(user);
	}

	@ResponseBody
	@PostMapping("/edit/save")
	@SystemLog(module = "系统设置", methods = "系统用户管理-更新用户")
	public AR update(@Validated(Edit.class) User user)  {
		return userService.update(user);
	}

	@ResponseBody
	@PostMapping("/add/checkUser")
	public AR checkUser(User user)  {
		if (StringUtil.isNotBlank(user.getUsername()) && userService.getByUserName(user.getUsername()) == null) {
			return AR.ok("登录账号不存在");  //注意，此处是ok，结合前端看
		} else if (StringUtil.isNotBlank(user.getPhone()) && userService.getByPhone(user.getPhone()) == null) {
			return AR.ok("手机号不存在");
		} else {
			return AR.failed("登录账号已存在，请重新输入");
		}
	}

	@ResponseBody
	@PostMapping("/del/deleteById")
	@SystemLog(module = "系统设置", methods = "系统用户管理-删除用户")
	public AR deleteById(@NotBlank(message = "ID为空，删除失败！") String id)  {
		return userService.logicById(id, 1);
	}

	@ResponseBody
	@PostMapping("/del/deleteByIds")
	@SystemLog(module = "系统设置", methods = "系统用户管理-批量删除用户")
	public AR deleteByIds(String ids)  {
		return userService.deleteBatchIds(ids);
	}

	@GetMapping("/list")
	@RequiresPermissions("sys:user:list")
	public String list(Model model)  {
		Boolean mutiOrg = Boolean.valueOf(SystemConfigureUtil.get(SystemConstants.MUTI_ORG));
		if(mutiOrg) {    //是否开启机构管理
			String roleScope = getUser().getType();
			//超管 或 所有机构权限 或 本机构及本机构下级权限 或 自定义机构  时显示机构树结构
			if("1".equals(getUser().getId()) || "1".equals(roleScope) || "2".equals(roleScope) || "4".equals(roleScope)){
				return "module/system/user/user-org-list";
			}else{
				model.addAttribute("orgId", getUser().getOrgId());
			}
		}
		return "module/system/user/user-list";
	}

	@ResponseBody
	@PostMapping("/list/listInfo")
	@SystemLog(module = "系统设置", methods = "系统用户管理-查询用户")
	public String userlist(User user, Page page, Model model)  {
		Boolean mutiOrg = Boolean.valueOf(SystemConfigureUtil.get(SystemConstants.MUTI_ORG));
		return JSONData.toLayerData(userService.list(page , user, mutiOrg));
	}

	/**
	 * @Author: lsq
	 * @Description: 根据需要初始化随机长度的密码
	 * @Date: 2022/2/24
	 **/
	@ResponseBody
	@PostMapping("/add/initPwd")
	@SystemLog(module = "系统设置", methods = "系统用户管理-初始化密码")
	public AR initPwd(@NotBlank(message = "ID为空，初始化失败！") String id)  {
			User user = new User();
			user.setId(id);
			String pd = CommonUtils.getRandomPassword(10);
			user.setPassword(pd);
			userService.update(user);
			return AR.ok("密码初始化成功,初始密码为："+pd);
	}

	@GetMapping("/add/setRole")
	public String setRole(String userId, Model model)  {
		model.addAttribute("userId", userId);
		return "module/system/user/set-role";
	}

	@ResponseBody
	@PostMapping("/add/userRole")
	public AR userRole(String userId)  {
		User user = userService.getById(userId);
		List<Role> roleList = Lists.newArrayList();
		if(SystemConfigureUtil.get(SystemConstants.MUTI_ORG).equals("true")){
			Role role = new Role();
			role.setOrgId(getUser().getOrgId());
			roleList = roleService.listAll(new QueryWrapper<>(role));
		}else{
			roleList = roleService.listAll(null);
		}
		List<Role> userRoleList = roleService.getRoleByUserId(userId);
		Map<String,Object> map = new HashMap<>();
		map.put("user",user);
		map.put("roleList",roleList);
		map.put("userRoleList",userRoleList);
		return AR.ok(map,"查询成功");
	}

	@ResponseBody
	@PostMapping("/add/setUserRole")
	public AR setUserRole(String userId, String roleIds)  {
		roleService.setUserRole(userId, roleIds);
		return AR.ok("设置成功！");
	}


	/*******根据用户查询已保存的自定义用户权限********/
	@ResponseBody
	@PostMapping("/add/orgInfo")
	public String orgInfo(String userId)  {
		List<String> compareMap = Lists.newArrayList();
		if(StringUtil.isNotBlank(userId)){
			User user = userService.getById(userId);
			compareMap = Arrays.asList(user.getOrgIds() == null ? null:user.getOrgIds().split(","));
		}
		DataScope dataScope= new DataScope();
		dataScope.setScopeName("id");
		List<Org> orgList = orgService.listAllTree(new QueryWrapper<>());
		String orgArray = "[";
		orgArray += getArrayTree(orgList, compareMap);
		int indx = orgArray.lastIndexOf(",");
		if (indx != -1)
			orgArray = orgArray.substring(0, indx);
		orgArray += "]";
		return orgArray;
	}

	private String getArrayTree(List<Org> list, List<String> compareMap) {
		String orgArray = "";
		for (int i = 0; i < list.size(); i++) {
			Org t = list.get(i);
			orgArray += "{id:\"" + t.getId() + "\"," + "pId:\"" + t.getParentId() + "\",name:\"" + t.getName() + "\"";
			if (compareMap.contains(t.getId())) {
				orgArray += ",checked:true";
			}
			if (t.getHasChild() == 1) {
				orgArray += ",isParent:true";
			}
			if (t.getChildren() != null && t.getChildren().size() > 0) {
				orgArray += ",open:true},";
				orgArray += getArrayTree(t.getChildren(), compareMap);
			} else {
				orgArray += "},";
			}
		}
		return orgArray;
	}

	@ResponseBody
	@RequestMapping("/updateDisable")
	@SystemLog(module = "系统设置", methods = "系统用户管理-禁用解禁用户")
	public AR updateDisable(@NotBlank(message = "ID为空不能为空！")  String id, String disable)  {
		User entity = new User();
		entity.setId(id);
		entity.setDisable(disable);
		userService.updateById(entity);
		return AR.ok(disable.equals("0")?"解禁成功":"禁用成功");
	}

	@ResponseBody
	@RequestMapping("/updateLockStatus")
	@SystemLog(module = "系统设置", methods = "系统用户管理-锁定解锁用户")
	public AR updateLockStatus(@NotBlank(message = "ID为空不能为空！")  String id, Integer lockStatus)  {
		User entity = new User();
		entity.setId(id);
		entity.setLockStatus(lockStatus);
		if(lockStatus == 1){
			entity.setLockTime(new Date());  //锁定时间
		}else {
			entity.setPwdCount(0);
		}
		userService.updateById(entity);
		return AR.ok(lockStatus==0?"解锁成功":"锁定成功");
	}

}
